<?php
namespace jy_weishop;
defined('BY_JYA') or exit('error');
/*
	优惠券
*/
class coupon extends \plugin{
	//赠送优惠券
	public function give_coupon($params,$noexi=false){
		$activity_tables=array(
				'goods'=>'coupon_goodsendtask',
				'order'=>'coupon_sendtasks',
				'new'=>'coupon_sendticket',
				'new_rate'=>'coupon_sendticket',
				'huodong'=>'coupon_huodongsendtask',
				'use'=>'coupon_usesendtasks',
				'pingjia'=>'coupon_sendtasks',
		);
		$table=$activity_tables[$params['ac_type']];
		$activity=$this->pdo_get($table,array('uniacid'=>$_SESSION['uniacid'],'id'=>$params['ac_id']));
		if(isset($activity['num']) && $activity['num']<$activity['sendnum']){
			return false;
		}
		if($params['ac_type']=='new_rate'){
			$activity['couponid']=$activity['ratecouponid'];
		}
		if(strpos($activity['couponid'], ';') !== false){
			$couponids=str_array($activity['couponid']);
		}else{
			$couponids=array();
			$couponids[]=$activity['couponid'];
		}
		foreach($couponids as $couponid){
			$canget=$this->checkcanget($couponid);
			if(!$canget){
				continue;
			}
		}
		if(!$canget){
			return false;
		}
		$give=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$params['mid'],
			'status'=>1,
			'createtime'=>TIMESTAMP,
			'remark'=>$params['remark'],
			'ac_id'=>$params['ac_id'],
			'ac_type'=>$params['ac_type'],
			'nolook'=>1,
		);
		$this->pdo_insert('coupon_wait',$give);
		$id=$this->pdo_insertid();
		//直接赠送
		$sendnum=$activity['sendnum']?:1;
		foreach($couponids as $couponid){
			for($i=0;$i<$sendnum;$i++){
				$this->getcoupon($couponid,$params['mid'],'',$noexi,'',$params['ac_type']);
			}
		}
		$setting=$this->plugin_setting('setting');
		$news=array(
					'title'=>'恭喜，您获得1张优惠券',
					'description'=>"快来查看吧！",
					'url'=>custom_url('jy_weishop/coupon.myindex/',true),
					'picurl'=>$setting['share_image'],
		);
		model('core/account')->send_news($news,$params['mid']);
		return true;
	}
	public function getcoupon($id=null,$mid=0,$nomax=false,$noexi=false,$merchid=0,$ac_type='',$gettype=2){
		if(!$id){
		    if($noexi){
                return false;
            }
			exi('优惠券不存在，请重新选择优惠券','error');
		}
		$mid=$mid?:$_SESSION['uid'];
		if(!$mid){
            if($noexi){
                return false;
            }
			exi('请先登录后，再领取！','error');
		}
		$coupon = pdo_get('jy_weishop_coupon',array('uniacid'=>$_SESSION['uniacid'],'id'=>$id));
		if(!$coupon['id']){
			return false;
		}
		$getallnum = pdo_count('jy_weishop_coupon_getlog',array('uniacid'=>$_SESSION['uniacid'],'couponid'=>$id));
		if($coupon['t'] <= $getallnum && $coupon['t']>0 && !$nomax){
            if($noexi){
                return false;
            }
			exi('不能再领了，已经上限了!','error');
		}
		$getnum = pdo_count('jy_weishop_coupon_getlog',array('uniacid'=>$_SESSION['uniacid'],'couponid'=>$id,'mid'=>$mid));
		$data1=array('mid'=>$mid,'merchid'=>$merchid?:$coupon['merchid'],'status'=>0,'uniacid'=>$_SESSION['uniacid'],'couponid'=>$id,'getfrom'=>0,'createtime'=>TIMESTAMP);
		$data2=array('mid'=>$mid,'merchid'=>$merchid?:$coupon['merchid'],'uniacid'=>$_SESSION['uniacid'],'couponid'=>$id,'ac_type'=>$ac_type,'gettype'=>$gettype,'createtime'=>TIMESTAMP);
		if($getnum && $coupon['getmax'] && $coupon['getmax'] <= $getnum && !$nomax){
            if($noexi){
                return false;
            }
			exi('不能再领了，已经上限了!','error');
		}
		$daytime = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$getdaynum = pdo_count('jy_weishop_coupon_getlog',array('createtime >'=>$daytime,'uniacid'=>$_SESSION['uniacid'],'couponid'=>$id,'mid'=>$mid));
		if($getdaynum && $coupon['daymax'] && $coupon['daymax'] <= $getdaynum && !$nomax){
            if($noexi){
                return false;
            }
			exi('不能再领了，已经上限了!','error');
		}
		pdo_update('jy_weishop_coupon',array('last -='=>1),array('uniacid'=>$_SESSION['uniacid'],'id'=>$id));
		pdo_insert('jy_weishop_coupon_getlog',$data2);
		pdo_insert('jy_weishop_coupon_log',$data1);
		return true;
	}
	public function checkcanget($id=null,$mid=0,$nomax=false){
		if(!$id){
			return false;
		}
		$mid=$mid?:$_SESSION['uid'];
		$coupon = pdo_get('jy_weishop_coupon',array('uniacid'=>$_SESSION['uniacid'],'id'=>$id));
		$getallnum = pdo_count('jy_weishop_coupon_getlog',array('uniacid'=>$_SESSION['uniacid'],'couponid'=>$id));
		if($coupon['t'] <= $getallnum && $coupon['t']>0 && !$nomax){
			return false;
		}
		$getnum = pdo_count('jy_weishop_coupon_getlog',array('uniacid'=>$_SESSION['uniacid'],'couponid'=>$id,'mid'=>$mid));
		if($getnum && $coupon['getmax'] && $coupon['getmax'] <= $getnum && !$nomax){
			return false;
		}
		$daytime = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$getdaynum = pdo_count('jy_weishop_coupon_getlog',array('createtime >'=>$daytime,'uniacid'=>$_SESSION['uniacid'],'couponid'=>$id,'mid'=>$mid));
		if($getdaynum && $coupon['daymax'] && $coupon['daymax'] <= $getdaynum && !$nomax){
             return false;
		}
		return true;
	}
	public function getorderfee($id=null,$orderprice=0,$goodsprice=0){
		$couponid=intval($id);
		$couponitem=pdo_get('jy_weishop_coupon_getlog',array('id'=>$couponid,'uniacid'=>$_SESSION['uniacid']));
		$coupon_detail=pdo_get('jy_weishop_coupon',array('id'=>$couponitem['couponid'],'uniacid'=>$_SESSION['uniacid']));
		$couponitem=array_merge($coupon_detail,$couponitem);
		if($couponitem){
			//使用优惠券
			$new_order['couponid']=$couponid;
			//折扣
			if($coupon_detail['backtype']==1){
				$new_order['coupon_discount']=$couponitem['discount'];
				if($new_order['coupon_discount']<=10 && $new_order['coupon_discount']>=0.1){
					$goodsprice=$goodsprice?:$orderprice;
					$disrate=100-$coupon_detail['discount']*10;
					$new_order['coupon_de_price']=intval($disrate*$goodsprice)/100;
					$discountmax=$coupon_detail['discountmax'];
					if($discountmax>0 && $discountmax<$goodsprice){
						$new_order['coupon_de_price']=intval($disrate*$discountmax)/100;
					}
				}
			}elseif($coupon_detail['backtype']==0){
				//立减
				$new_order['coupon_de_price']=$couponitem['deduct'];
			}
			if($new_order['coupon_de_price']){
				$new_order['price']=$orderprice-$new_order['coupon_de_price'];
			}
		}
		return $new_order;
	}
	public function getmycoupon_ing($coupontype=1,$goodsprice=0,$level_de_price='',$orders='',$enough_de_price=0,$page=0,$mid=0,$pluginname=''){
		//整理优惠券数据，先获取用户所有待使用优惠券，再从中筛选出未过期的优惠券且本次下单可用的优惠券！
		$coupons=$this->getmycoupon('','','',$page,$mid);
		$couponset=$this->plugin_setting('coupon');
		if($coupons){
			if($this->plugin_exists('jy_merch')){
				$jy_merch=true;
			}
			$newcoupons=array();
			foreach($coupons as $key=>$coupon){
				$coupon_detail=pdo_get('jy_weishop_coupon',array('id'=>$coupon['couponid'],'coupontype'=>$coupontype,'uniacid'=>$_SESSION['uniacid']));
				if($coupon_detail['backtype']==2){
					$coupon_detail['deduct']=0;
				}
				if(!$coupon_detail){
					unset($coupons[$key]);
					continue;
				}
				if(!$coupon_detail['status']){
					//优惠券状态为不可用
					//unset($coupons[$key]);
					//continue;
				}
				//仅插件可使用
				$pluginname=$pluginname?:$_SESSION['current_plugin'];
				if($coupon_detail['pluginname'] && $pluginname && $pluginname!=$coupon_detail['pluginname']){
					unset($coupons[$key]);
					continue;
				}
				//判断有效期
				if($coupon_detail['timelimittype']==1){
					//有效期类型为领取后若干天内使用
					$days=(TIMESTAMP-$coupon['createtime'])/86400;
					if($coupon_detail['timedays']<$days){
						//已过期
						unset($coupons[$key]);
						continue;
					}
				}elseif($coupon_detail['timelimittype']==2){
					$coupon_detail['limittimes']=json_decode($coupon_detail['limittimes'],true);
					if(TIMESTAMP<$coupon_detail['limittimes']['tstart'] || TIMESTAMP>$coupon_detail['limittimes']['tend']){
						//不在有效期内
						unset($coupons[$key]);
						continue;
					}
				}
				//判断购物券是否当前可用
				if($orders){
					$check=false;
					foreach($orders as $g){
						if(!$coupon_detail['merchid'] && $couponset['is_merch']){
							$check=true;
							break;
						}
						if(isset($g['merchid'])){
							$merchid=$g['merchid'];
						}else{
							$merchid=pdo_getcolumn('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$g['goodsid']),'merchid');
						}
						if($coupon_detail['merchid'] && $merchid && $merchid!=$coupon_detail['merchid'] && !$coupon_detail['ismerch']){
							continue;
						}elseif($merchid!=$coupon_detail['merchid'] && !$coupon_detail['ismerch']){
							continue;
						}else{
							$check=true;
						}
					}
					if(!$check){
						//不可用
						unset($coupons[$key]);
						continue;
					}
				}
				if($coupontype==1){
					$neworders=$orders;
					if($coupon_detail['limitgoodtype']){
						$coupon_detail['limitgoodids']=str_array($coupon_detail['limitgoodids']);
						$check=false;
						if($neworders){
						    //支持该优惠券的商品额度
							foreach($neworders as $k=>$g){
								if(in_array($g['goodsid'],$coupon_detail['limitgoodids'])){
								}else{
									unset($neworders[$k]);
								}
							}
						}	
					}
					if($coupon_detail['limitgoodcatetype']){
						$coupon_detail['limitgoodcateids']=str_array($coupon_detail['limitgoodcateids']);
						$check=false;
						if($neworders){
                            //支持该优惠券的商品额度
							foreach($neworders as $k=>$g){
								if(in_array($g['pcate'],$coupon_detail['limitgoodcateids']) || in_array($g['ccate'],$coupon_detail['limitgoodcateids'])){
								}else{
									unset($neworders[$k]);
								}
							}
						}
					}
					//多商户
					if($jy_merch && $coupon_detail['ismerch']==1 && $coupon_detail['merchtype']){
						$check=false;
						$ismerch=true;
						foreach($neworders as $k=>$g){
							if(strpos($coupon_detail['limitmerchids'],';'.$g['merchid'].';') !== false){
								continue;
							}else{
								unset($neworders[$k]);
							}
						}
					}
					if($coupon_detail['limitgoodtype'] || $coupon_detail['limitgoodcatetype'] || $ismerch){
						$cantotalprice=0;
						foreach($neworders as $k=>$g){
							 $cantotalprice +=$g['price']*$g['total'];
						}
						if($cantotalprice>0 && $cantotalprice>=$coupon_detail['enough']){
									$check=true;
									switch($coupon_detail['backtype']){
										case 0://立减
											$coupon['de_price']=$coupon_detail['deduct'];
											$coupon['content']="满{$coupon_detail['enough']}减{$coupon_detail['deduct']}";
											break;
										case 1://折扣
											$disrate=100-$coupon_detail['discount']*10;
											$coupon['de_price']=intval($disrate*$cantotalprice)/100;
											$coupon['content']="满{$coupon_detail['enough']}打{$coupon_detail['discount']}折";
											$discountmax=$coupon_detail['discountmax'];
											if($discountmax>0 && $discountmax<$cantotalprice){
												$coupon['de_price']=intval($disrate*$discountmax)/100;
											}
											break;
										case 2://返利
											$coupon['de_price']=0;
											$coupon['content']="满{$coupon_detail['enough']}返{$coupon_detail['backmoney']}余额，{$coupon_detail['backcredit']}积分，{$coupon_detail['backredpack']}现金";
											break;
										default:
											$coupon['de_price']=0;
											$coupon['content']='';
									}
						 }
						 if(!$check){
							//不可用
							unset($coupons[$key]);
							continue;
						}
					}else{
							switch($coupon_detail['backtype']){
											case 0://立减
												$coupon['de_price']=$coupon_detail['deduct'];
												$coupon['content']="满{$coupon_detail['enough']}减{$coupon_detail['deduct']}";
												break;
											case 1://折扣
												$disrate=100-$coupon_detail['discount']*10;
												$coupon['de_price']=intval($disrate*$goodsprice)/100;
												$coupon['content']="满{$coupon_detail['enough']}打{$coupon_detail['discount']}折";
												$discountmax=$coupon_detail['discountmax'];
												if($discountmax>0 && $discountmax<$goodsprice){
													$coupon['de_price']=intval($disrate*$discountmax)/100;
												}
												break;
											case 2://返利
												$coupon['de_price']=0;
												$coupon['content']="满{$coupon_detail['enough']}返{$coupon_detail['backmoney']}余额，{$coupon_detail['backcredit']}积分，{$coupon_detail['backredpack']}现金";
												break;
											default:
												$coupon['de_price']=0;
												$coupon['content']='';
							}
					}
					if($goodsprice && $coupon_detail['enough'] && $goodsprice<$coupon_detail['enough']){
						//不可用
						unset($coupons[$key]);
						continue;
					}
				}
				$coupon=array_merge($coupon_detail,$coupon);
				if($coupons[$key]){
					//判断使用限制
					if($coupon_detail['limitusetype']){
						switch($coupon_detail['limitusetype']){
							case 1://不可与促销优惠同时使用
								if($enough_de_price){
									$coupon['noenough_de_price']=1;
									if($coupon['de_price']<$enough_de_price){
										unset($coupons[$key]);
										continue;
									}
								}
							case 2://不可与会员折扣同时使用
								if($level_de_price){
									$coupon['nolevel_de_price']=1;
									if($coupon['de_price']<$level_de_price){
										unset($coupons[$key]);
										continue;
									}
								}
							case 3://不可与促销、折扣同时使用
								if($level_de_price){
									$coupon['nolevel_de_price']=1;
									if($coupon['de_price']<$level_de_price){
										unset($coupons[$key]);
										continue;
									}
								}
								if($enough_de_price){
									$coupon['noenough_de_price']=1;
									if($coupon['de_price']<$enough_de_price){
										unset($coupons[$key]);
										continue;
									}
								}
						}
					}
					if($coupons[$key]){
						$newcoupons[]=$coupon;
					}
				}
			}
		}
		if(!empty($newcoupons)){
			//存在可用优惠券，选择一个抵扣金额最大的作为默认选中的优惠券
			paixu($newcoupons,'de_price','desc');
		}
		return $newcoupons;
	}
	public function getmycoupon($status='',$type='',$past='',$page=0,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$p=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid);
		if($status==1){
			$p=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'isuse'=>1);
		}elseif($status==2){
			$p=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'islock'=>1,'isuse'=>0);
		}else{
			$p=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'islock'=>0,'isuse'=>0);
		}
		$return['status'] = $status ? $status :0;
		$pindex = max(1,$page);
		$total='';
		if($page){
			if(intval($_RQ['num'])){
				$psize = intval($_RQ['num']);
			}else{
				$psize = 10;
			}
		}else{
			$psize = 60;
		}
		$list=pdo_getslice('jy_weishop_coupon_getlog',$p,array($pindex,$psize),$total,$fields,'','id desc');
		foreach($list as $k=>&$v){
			$couponinfo=pdo_get('jy_weishop_coupon',array('uniacid'=>$_SESSION['uniacid'],'id'=>$v['couponid']));
			if($couponinfo['coupontype']==$type && $type){
				if($couponinfo['timelimittype']==1){
					$time=$v['createtime']+$couponinfo['timedays']*24*3600;
					if(time()<$time){
						$coupon=$this->intcoupon($v['couponid'],$v['createtime']);
						$coupons[]=array('id'=>$v['id'],'coupon'=>$coupon);
					}
				}elseif($couponinfo['timelimittype']==2){
					$couponinfo['limittimes']=json_decode($couponinfo['limittimes'],true);
					if($couponinfo['limittimes']['tstart']<time() && $couponinfo['limittimes']['tend']>time()){
						$coupon=$this->intcoupon($v['couponid'],$v['createtime']);
						$coupons[]=array('id'=>$v['id'],'coupon'=>$coupon);
					}
				}else{
					$coupon=$this->intcoupon($v['couponid'],$v['createtime']);
					$coupons[]=array('id'=>$v['id'],'coupon'=>$coupon);
				}
			}
			$v['coupon']=$this->intcoupon($v['couponid'],$v['createtime']);
			if(!$v['coupon']['id']){
				unset($list[$k]);
			}
			if($status==0 && $v['coupon']['past']==1){
				//删除已过期
				unset($list[$k]);
			}
			if($status==3 && $v['coupon']['past']!=1){
				//删除未过期
				unset($list[$k]);
			}
		}
		$list=array_values($list);
		return $list;
	}
	//整理一下券
	public function intcoupon($id,$createtime=0,$merchid=0){
			$coupon=pdo_get('jy_weishop_coupon',array('uniacid'=>$_SESSION['uniacid'],'id'=>$id));
			$coupon['limittimes']=json_decode($coupon['limittimes'],true);
			$title2 = '';
			$title3 = '';
			$coupon['isdisa'] = 0;
			if ($coupon['t'] >=1){
					$getallnum = pdo_count('jy_weishop_coupon_getlog',array('uniacid'=>$_SESSION['uniacid'],'couponid'=>$id));
					if ($getallnum >= $coupon['t']){
						$coupon['last'] = 0;
						$coupon['isdisa'] = '1';
					}else{
						$totle = $coupon['t'];
						$coupon['last'] = $coupon['t']-$getallnum;
						$coupon['lastratio'] = intval(($coupon['last'] / $totle) * 100);
					}
			}else{
					$coupon['last'] = 1;
					$coupon['lastratio'] = 100;
			}
			if($coupon['coupontype'] == '1'){
				if (0 < $coupon['enough']) {
					$title2 = '满' . (double) $coupon['enough'] . '元可用';
				}
				else {
					$title2 = '无金额门槛';
				}
			}elseif($coupon['coupontype'] == '2'){
				if (0 < $coupon['enough']) {
					$title2 = '充值满' . (double) $coupon['enough'] . '元可用';
				}else{
					$title2 = '无金额门槛';
				}
			}
			if ($coupon['backtype'] == 0) {
				if ($coupon['enough'] == '0') {
					$coupon['color'] = 'orange';
				}
				else {
					$coupon['color'] = 'blue';
				}

				$title3 = '￥' . (double) $coupon['deduct'];
			}
			if ($coupon['backtype'] == 0){
					if ($coupon['enough'] == '0') 
					{
						$title5 = '任意金额立减' . (double) $coupon['deduct'];
						$coupon['color'] = 'orange ';
						$coupon['tagtitle'] = '代金券';
					}
					else 
					{
						$title5 = '满' . (double) $coupon['enough'] . '立减' . (double) $coupon['deduct'].'元';
						$coupon['color'] = 'blue';
						$coupon['tagtitle'] = '满减券';
					}
			}elseif ($coupon['backtype'] == 1) {
					$coupon['color'] = 'red ';
					$coupon['tagtitle'] = '打折券';
					if ($coupon['enough'] == '0') 
					{
						$title5 = '任意金额' . '打' . (double) $coupon['discount'] . '折';
					}
					else 
					{
						$title5 = '满' . (double) $coupon['enough'] . '打' . (double) $coupon['discount'] . '折';
					}
					if($coupon['discountmax']>0){$title5 = $title5.',超过'. (double) $coupon['discountmax'].'部分不打折';}
			}elseif ($coupon['backtype'] == 2) {
					//重置优惠金额
					$coupon['deduct']=0;
					if ($coupon['coupontype'] == '0') 
					{
						$coupon['color'] = 'red ';
						$coupon['tagtitle'] = '购物返现券';
					}
					elseif ($coupon['coupontype'] == '1') 
					{
						$coupon['color'] = 'pink ';
						$coupon['tagtitle'] = '购物返现券';
					}
					elseif ($coupon['coupontype'] == '2') 
					{
						$coupon['color'] = 'red ';
						$coupon['tagtitle'] = '充值返现券';
					}
					if ($coupon['enough'] == '0') 
					{
						$title5 = '任意金额';
					}
					else 
					{
						$title5 = '满' . (double) $coupon['enough'];
					}
					if (!(empty($coupon['backmoney'])) && (0 < $coupon['backmoney'])) 
					{
						$title3 = '立返';
						$title5 = $title5 . '立返余额'.$coupon['backmoney'];
					}
					elseif (!(empty($coupon['backcredit'])) && (0 < $coupon['backcredit'])) 
					{
						$title3 = '立返';
						$title5 = $title5 . '立返积分'.$coupon['backcredit'];
					}
					elseif (!(empty($coupon['backredpack'])) && (0 < $coupon['backredpack'])) 
					{
						$title5 = $title5 . '立返红包'.$coupon['backcredit'];
					}
			}
			if ($coupon['backtype'] == 1) {
				$coupon['color'] = 'red ';
				$title3 = (double) $coupon['discount'] . '折 ';
			}
			if ($coupon['backtype'] == 2) {
				if ($coupon['coupontype'] == '0') {
					$coupon['color'] = 'red ';
				}else {
					$coupon['color'] = 'pink ';
				}

				if (!empty($coupon['backmoney']) && (0 < $coupon['backmoney'])) {
					$backmoneytext = $coupon['backmoney'] . '元余额 ';
				}

				if (!empty($coupon['backcredit']) && (0 < $coupon['backcredit'])) {
					$backcredittext = $coupon['backcredit'] . '积分 ';
				}

				if (!empty($coupon['backredpack']) && (0 < $coupon['backredpack'])) {
					$backredpacktext = $coupon['backredpack'] . '元红包';
				}
			}
			if ($coupon['tagtitle'] == '') {
					$coupon['tagtitle'] = $tagtitle;
			}
			if ($coupon['timelimittype'] == '0') {
					$title4 = '永久有效';
			}elseif ($coupon['timelimittype'] == '1') {
					$title4 = '领取' . $coupon['timedays'] . '天内有效';
			}else{
					$title4 = date('Y/m/d',$coupon['limittimes']['tstart']).'~'.date('Y/m/d',$coupon['limittimes']['tend']);
			}
			if($coupon['coupontype'] == '3'){
				$coupon['reward']=json_decode($coupon['reward'],true);
				$num=count($coupon['reward']);
				$coupon['tagtitle'] = '礼品券';
				$title2 = $num.'个礼包';
				$title3 = '礼品券';
				$title4 = '限时领取';
				$title5 = '内含'.$num.'个礼品';
			}
			$coupon['title2'] = $title2;
			$coupon['title3'] = $title3;
			$coupon['title4'] = $title4;
			$coupon['title5'] = $title5;
			if($coupon['merchid']){
				$coupon['merchname']=pdo_getcolumn('jy_merch_user',array('id'=>$coupon['merchid'],'uniacid'=>$_SESSION['uniacid']),'merchname');
			}
			$coupon['past']=0;
			if($coupon['timelimittype']==1){
				$time=$createtime+$coupon['timedays']*24*3600;
				if(time()>$time){
					$coupon['past']=1;
					$coupon['time']=date('Y/m/d',$time);
				}else{
					$start=$createtime;
					$start=date('Y/m/d',$start);
					$time=date('Y/m/d',$time);
					$coupon['time']=$start.'至'.$time;
				}
			}
			if($coupon['timelimittype']==2){
				if(time()>$coupon['limittimes']['tend']){
					$coupon['past']=1;
					$coupon['time']=date('Y/m/d',$coupon['limittimes']['tend']);
				}else{
					$coupon['limittimes']['tstart']=date('Y/m/d',$coupon['limittimes']['tstart']);
					$coupon['limittimes']['tend']=date('Y/m/d',$coupon['limittimes']['tend']);
					$coupon['time']=$coupon['limittimes']['tstart'].'至'.$coupon['limittimes']['tend'];
				}
			}
			//多商户适用
			if($merchid && $coupon['ismerch']==1 && $coupon['merchtype']){
				if(strpos($coupon['limitmerchids'],';'.$merchid.';') !== false){
				}else{
					$coupon['nomerch']=1;
				}
			}
		return $coupon;
	}
	public function usecoupon($id,$ordersn='',$mid=0){
		$couponid=intval($id);
		$getlog=pdo_get('jy_weishop_coupon_getlog',array('id'=>$couponid,'uniacid'=>$_SESSION['uniacid']),array('mid','couponid','ac_type'));
		$mid=$mid?:$getlog['mid'];
		$coupon_detailid=$getlog['couponid'];
		$coupon_detail=pdo_get('jy_weishop_coupon',array('id'=>$coupon_detailid,'uniacid'=>$_SESSION['uniacid']));
		if($coupon_detailid && $coupon_detail['backtype']=='2'){
			//使用优惠券
			if($coupon_detail['backmoney']){
				model('core/member')->add_credit2($mid,$coupon_detail['backmoney'],'返余额');
			}
			if($coupon_detail['backcredit']){
				model('core/member')->add_credit1($mid,$coupon_detail['backcredit'],'返积分');
			}
			if($coupon_detail['backredpack']){
				$params=array(
					'mid'=>$mid,
					'money'=>$coupon_detail['backredpack'],
					'remark'=>'返现金红包',
				);
				model('core/red_pack')->get_money($params);
			}
		}
		if($coupon_detail['coupontype']=='3'){
			$reward=json_decode($coupon_detail['reward'],true);
			if($coupon_detail['ismerch']==1){
				$limitmerchids=str_array($coupon_detail['limitmerchids']);
			}
			foreach($reward as $rv){
				if($rv['type']==1){
					$isgoods=1;
				}elseif($rv['type']==9){
					if($rv['couponid']){
						$this->model('coupon')->getcoupon($rv['couponid'],$mid,1);
					}
				}elseif($rv['type']==7){
					$red_max=$rv['rexmax']?:0;
					$red_min=$rv['redmin']?:0;
					$fee=mt_rand($red_min*100,$red_max*100);
					$fee=$fee/100;
					$red=array(
						'mid'=>$mid,
						'money'=>$fee,
						'plugin'=>'jy_weishop_liping',
						'remark'=>'礼品券送红包',
					);
					cfc('red_pack')->get_money($red);
				}else{
					$credittype=$rv['type']==2?1:$rv['type'];
					if($rv['jifen']>0){
						if($coupon_detail['ismerch']==1){
							foreach($limitmerchids as $merchid){
								model('jy_merch/member')->addcreditlog($merchid,'',$rv['jifen'],$credittype,1);
							}
						}else{
							cfc('core')->member_credit($mid,'credit'.$credittype,$rv['jifen'],1,'jy_weishop_liping','礼品券');
						}
					}
				}
			}
		}
		pdo_update('jy_weishop_coupon_getlog',array('isuse'=>1,'usetime'=>TIMESTAMP,'ordersn'=>$ordersn),array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		//用券送券
		$usesendtasks=pdo_get('jy_weishop_coupon_usesendtasks',array('usecouponid'=>$coupon_detailid,'uniacid'=>$_SESSION['uniacid']));
		if($usesendtasks['couponid']){
			$params=array(
					'mid'=>$mid,
					'ac_type'=>'use',
					'ac_id'=>$usesendtasks['id'],
					'remark'=>'用券送券活动',
			);
			$this->give_coupon($params);
		}
		//用新人券，推荐人的券
		$fromuser=pdo_getcolumn('core_members',array('id'=>$mid,'uniacid'=>$_SESSION['uniacid']),'fromuser');
		if($fromuser){
			$newquan=pdo_get('jy_weishop_coupon_sendticket',array('type'=>0,'uniacid'=>$_SESSION['uniacid']));
		}
		if($newquan['is_rate'] && $newquan['ratecouponid']){
			$params=array(
					'mid'=>$fromuser,
					'ac_type'=>'new_rate',
					'ac_id'=>$newquan['id'],
					'remark'=>'用新人券推荐人得券活动',
			);
			$this->give_coupon($params);
		}
		return true;
	}
	//获取优惠券
	public function getmerchcoupon($merchid,$coupontype=0,$issend=1){
		$params = array('uniacid'=>$_SESSION['uniacid'],'status'=>1);
		if($merchid){
			$params['merchid']=$merchid;
		}
		if($coupontype){
			$params['coupontype']=$coupontype;
		}
		$levelinfo=pdo_getcolumn('jy_weishop_member',array('merchid'=>$merchid?:0,'mid'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']),'level');//会员等级信息
		$params['memberlevels OR']='islimitlevel=0 or memberlevels=\'\' or memberlevels like \'%;'.trim($levelinfo).';%\'';//等级领取权限
		$getcoupon=pdo_getall('jy_weishop_coupon',$params);
		foreach($getcoupon as $k=>&$item){
			$limittimes2=json_decode($item['limittimes'],true);
			if($item['issendtime']){
				$item['sendtime']=$item['sendtime']?json_decode($item['sendtime'],true):array();
				$item['etime']=$item['sendtime']['tend'];
				if($item['sendtime']['tstart']>time()){
					$item['issend']=0;
					$item['etime']=$item['sendtime']['tstart'];
				}elseif($item['sendtime']['tstart']<time() && $item['sendtime']['tend']>time()){
					$item['issend']=1;
					$item['etime']=$item['sendtime']['tend'];
				}elseif($item['sendtime']['tend']<time()){
					$item['issend']=2;
					if($issend){//剔除过期的
						continue;
					}
				}
				$item['sendtime']['tend2']=$item['sendtime']['tend'];
				$item['sendtime']['tstart2']=$item['sendtime']['tstart'];
				$item['sendtime']['tend']=date('Y-m-d',$item['sendtime']['tend']);
				$item['sendtime']['tstart']=date('Y-m-d',$item['sendtime']['tstart']);
			}else{
				$item['issend']=1;
			}
			if($item['timelimittype']==2 && $limittimes2['tend']<time()){
				continue;
			}else{
				$item=$this->intcoupon($item['id']);
				$coupons[]=$item;
			}	
		}
		return $coupons;
	}
	public function getordergoods($couponlogid=0){
		$log=pdo_get('jy_weishop_coupon_getlog',array('uniacid'=>$_SESSION['uniacid'],'id'=>$couponlogid));
		if(!$log){
			exi('礼品券不存在，不能兑换商品！','error');
		}
		if($log['ordersn']){
			exi('礼品券已经兑换商品！','error');
		}
		if($log['mid']!=$_SESSION['uid']){
			exi('礼品券不是您的，不能使用！！','error');
		}
		$cart_list=array();
		$coupon_detail=pdo_get('jy_weishop_coupon',array('id'=>$log['couponid'],'uniacid'=>$_SESSION['uniacid']));
		if($coupon_detail['coupontype']=='3'){
			$reward=json_decode($coupon_detail['reward'],true);
			foreach($reward as $rv){
				if($rv['type']==1){
					$isgoods=1;
					$cart_list[]=array('total'=>1,'goodsid'=>$rv['goodsid']);
				}
			}
		}
		if(!$isgoods){
			exi('该礼品券没有任何商品可兑换！！','error');
		}
		$diyfields=array();
		foreach($cart_list as $k=>&$cart){
			if(!$cart['goodsid']){
				unset($cart_list[$k]);
				continue;
			}
			$goodsfile=array('id','fang_credit2','no_de_sales','isdiyprice','diyprice','invoice','type','buylevels','buygroups','title','merchid','status','pcate','ccate','total','subtitle','image','video','price','totalcnf','weight','active_plugin','active_id','storeids','salenum','pluginname','originalprice','usermaxbuy','minbuynum','unit','isverify','diyfields','api_id','api_pluginname');
			$goods=pdo_get('jy_weishop_goods',array('id'=>$cart['goodsid'],'uniacid'=>$_SESSION['uniacid']),$goodsfile);
			if(!$goods){
				exi('指定商品不存在！','error','goback');
			}
			$goods['weight']=pdo_getcolumn('jy_weishop_goods_dispatch',array('goodsid'=>$cart['goodsid'],'uniacid'=>$_SESSION['uniacid']),'weight');
			if(($merchid>0 && $goods['merchid']!=$merchid) || ($merchid<0 && $goods['merchid'])){
				unset($cart_list[$k]);
				continue;			
			}
			if($_SESSION['is_tomedia']){
				$goods['image']=$goods['image']?tomedia($goods['image']):'';
			}
			$goods['diyfields']=$this->model('goods')->get_diyformfields($cart['goodsid']);
			if($goods['diyfields']){
				$diyfields=$goods['diyfields'];
			}
			//配送设置
			$goodsdispatch=$this->model('goods')->get_dispatch($cart['goodsid']);
			$goods=array_merge($goods,$goodsdispatch);
			$goods['storeid']=$store_id;
			$goods['optionid']=$cart['optionid'];
			$goods=$this->model('activity')->get_upgoods($goods);
			if($goods['active']['dian_mid']){
				$goods['merchid']=pdo_getcolumn('jy_merch_user',array('mid'=>$goods['active']['dian_mid'],'uniacid'=>$_SESSION['uniacid']),'id');
				$merchid=$goods['merchid'];
			}
			//重置下单数量
			$goods['goodstotal']=$goods['total'];
			if($cart['optionid']){
				if(!$goods['options']){
					exi('指定规格的商品不存在！','error','goback');
				}
				if(!$goods['options']['specs']){
					$optiontitle=$goods['options']['title'];
					$goods['istaocan'] = 1;
				}else{
					$goods['price']=$goods['options']['price'];
					$specs = explode("_", $goods['options']['specs']);
					$specsall = pdo_getall('jy_weishop_goods_spec_item',array('id'=>$specs,'uniacid'=>$_SESSION['uniacid']),array('id','title'),'','paixu asc');
					if($specsall){
						$optiontitle='';
						foreach($specsall as $k=>&$sp){
							if($k==0){
								$optiontitle .=$sp['title'];
							}else{
								$optiontitle .='，'.$sp['title'];
							}
						}
					}
				}
				$goods['optiondata']= $optiontitle;
				$goods['weight']=$goods['options']['weight']?:$goods['weight'];
			}
			//来自商户的分销
			$cart['merchid']=$cart['merchid']?$cart['merchid']:$goods['merchid'];
			if($goods['type']==1 || $goods['type']==2){
				//虚拟商品
				$order['sendtype']=3;
			}elseif($goods['type']==3){
				//计时计次服务，发货类型必须是上门核销
				$order['sendtype']=2;
			}elseif($goods['type']==0 || $goods['isverify']){
				//实体商品，查找是否有门店，如果有门店则表示支持自提，否则只能是快递配送
				$issendtype=1;
				if(!$carrier_list || (($merchid<=0 || !$merchid) && !$goods['isverify'] && !$shopset['is_sendtype2'])){
					$order['sendtype']=1;
				}else{
					$return['sendtypes']=array(
						'1'=>'快递配送',
						'2'=>'自提',
					);
				}
			}
			$cart=array_merge($goods,$cart);
			$cart['cartid']=$cart['id'];
			$cart['id']=$goods['id'];
		}
		if($issendtype && $issendtype!=$order['sendtype'] && !$return['sendtypes']){
			$order['sendtype']=1;
		}
		$cart_list=array_values($cart_list);
		$res=array(
			'sendtype'=>$order['sendtype'],
			'sendtypes'=>$return['sendtypes'],
			'diyfields'=>$diyfields,
			'cart_list'=>$cart_list,
		);
		return $res;
	}
}